#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
//#include "node.c"

extern void server_start();

extern void server_close();

int is_close = 0;
int serv_sock;
int clnt_sock;

void server_start()
{
    serv_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    struct sockaddr_in serv_addr;
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(1234);
    serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    bind(serv_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
    is_close = 1;
    listen(serv_sock, 20);
    int i = 0;
    FILE *fp = NULL;
    //fp = fopen("/home/xiefeihong/下载/0.mp4", "r");
    fp = fopen("/home/xiefeihong/下载/test.txt", "r");

    while (is_close){
        struct sockaddr_in clnt_addr;
        socklen_t clnt_addr_size = sizeof(clnt_addr);
        clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_addr, &clnt_addr_size);

        char buff[255];

        /*struct node *n;
        n->buff = buff;*/
        int fd = 0;
        while(fgets(buff, 255, fp) != NULL){

            /*n = n->next;
            n->buff = buff;
            printf("%d, %s\n", n->id, n->buff);*/

            printf("server send message: %s\n", buff);
            write(clnt_sock, buff, sizeof(buff));
            //send(fd, buff, sizeof(buff), 0);

        }
        fclose(fp);

//        char a[] = "Hello World";
//        char s2[20];
//        sprintf(s2, "%s%d", a, i);
//        write(clnt_sock, s2, sizeof(s2));
//        i ++;
    }

}

void server_close()
{
    is_close = 0;
    close(clnt_sock);
    close(serv_sock);
}